//
//  KcSelectImageShowView.swift
//  Pods
//
//  Created by 张杰 on 2017/9/1.
//
//

import UIKit
import MWPhotoBrowsers_zdst
import AVFoundation

/* demo
 fileprivate lazy var selectImage: KcSelectImageShowView = {
     let h = KcSelectImageShowView.getHeight(UIScreen.main.bounds.size.width, array: nil, maxImagesCount: 9)
     let select = KcSelectImageShowView(CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: h), viewController: self, maxImagesCount: 9)
     select.delegate = self
     return select
 }()
 
 //回调，获得image数组，更新frame
 extension ViewController: KcSelectImageShowViewDelegate {
     func kcSelectImageShowView(_ selectImageView: KcSelectImageShowView, finishImageArray: [UIImage]?, contentHeight: CGFloat) {
         selectImage.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: contentHeight)
     }
 }
*/
@objc public protocol KcSelectImageShowViewDelegate {
    @objc optional func kcSelectImageShowView(_ selectImageView: KcSelectImageShowView, finishImageArray: [UIImage]?, contentHeight: CGFloat)
}

public class KcSelectImageShowView: UIView {

    /// 回调
    public weak var delegate: KcSelectImageShowViewDelegate?
    public var finishBlock: ((_ selectImageView: KcSelectImageShowView,_ finishImageArray: [UIImage]?,_ contentHeight: CGFloat) -> Void)?
    
    /// 初始化func
    public init(_ frame: CGRect, viewController: UIViewController, maxImagesCount: Int) {
        self.viewController = viewController
        self.maxImagesCount = maxImagesCount
        super.init(frame: frame)
        
        selectImageTool = KcSelectImageTool(viewController, maxImagesCount: maxImagesCount)
        
        addSubview(collectionView)
    }
    
    /// 初始化添加照片显示
    public func appendImage(_ array: [String]?) {
        guard let a = array else { return }
        if a.count > maxImagesCount {
            print("照片数量错误")
            return
        }
        for i in a {
            let icon = UIImage(named: i)
            if icon == nil { return }
            arrayImage.append(icon!)
        }
        collectionView.reloadData()
    }
    
    /// 求控件的高度
    public static func getHeight(_ contentW: CGFloat, array: [Any]?, maxImagesCount: Int) -> CGFloat {
        
        let k = 3
        let itemW = (contentW - CGFloat(10 * (k - 1))) / CGFloat(k)
        var count = 1
        if array != nil {
            if array!.count >= maxImagesCount {
                count = (maxImagesCount - 1) / k + 1
            }
            else {
                count = array!.count / k + 1
            }
        }
        return (itemW + 10) * CGFloat(count) - 10
    }
    
    //MARK: 懒加载
    fileprivate weak var viewController: UIViewController?
    fileprivate let maxImagesCount: Int
    
    fileprivate var arrayImage: [UIImage] = {
        let arrayImage = [UIImage]()
        return arrayImage
    }()
    
    fileprivate lazy var layout: KcPhoneFlowLayout = {
        let layout = KcPhoneFlowLayout()
        return layout
    }()
    
    fileprivate lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.register(KcPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "KcPhotoCollectionViewCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        return collectionView
    }()
    fileprivate var selectImageTool: KcSelectImageTool?//选择相册图片
    fileprivate lazy var alertSheet: UIAlertController = { [weak self] in
        let alertSheet = UIAlertController(title: "选择图片", message: nil, preferredStyle: .actionSheet)
        let cancel = UIAlertAction(title: "取消", style: .cancel) { (action: UIAlertAction) in
            
        }
        let camera = UIAlertAction(title: "选择相机", style: .default) { [weak self] (action: UIAlertAction) in
            self?.openCamera()
        }
        let brower = UIAlertAction(title: "选择相册", style: .default) { [weak self] (action: UIAlertAction) in
            self?.selectImageTool?.show((self?.maxImagesCount)! - (self?.arrayImage.count)!, finishBlock: { [weak self] (array: [UIImage]?) in
                guard let a = array else { return }
                for i in a {
                    self?.arrayImage.append(i)
                }
                self?.callback()
            })
        }
        
        alertSheet.addAction(cancel)
        alertSheet.addAction(camera)
        alertSheet.addAction(brower)
        return alertSheet
    }()
    
    // 获取bundle中的图片
    fileprivate lazy var icon_select: UIImage? = {
        let path = Bundle(for: KcPhotoView.self).resourcePath! + "/KCSelectIcon.bundle"
        let CABundle = Bundle(path: path)
        let image = UIImage(named: "general_btn_addphoto", in: CABundle, compatibleWith: nil)
        return image
    }()
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KcSelectImageShowView: UICollectionViewDataSource,UICollectionViewDelegate {
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrayImage.count == maxImagesCount ? arrayImage.count : arrayImage.count + 1
    }
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = KcPhotoCollectionViewCell.cellWithCollectionView(collectionView, indexPath: indexPath)
        if arrayImage.count == maxImagesCount {//为最大的个数，不可再添加
            cell.icon.image = arrayImage[indexPath.row]
        }
        else {//有添加功能
            if indexPath.row == collectionView.numberOfItems(inSection: 0) - 1 {//最后1个为+
                cell.icon.image = icon_select
            }
            else {
                cell.icon.image = arrayImage[indexPath.row]
            }
        }
        return cell
    }
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if arrayImage.count == maxImagesCount {//为最大的个数，不可再添加
            showPhotoBrower(indexPath.row)
        }
        else {
            if indexPath.row == collectionView.numberOfItems(inSection: 0) - 1 {//最后1个为+
                viewController?.present(alertSheet, animated: true, completion: nil)
            }
            else {
                showPhotoBrower(indexPath.row)
            }
        }
    }
    
    //放大图片
    private func showPhotoBrower(_ index: Int) {
        let brower = SDPhotoBrowser()
        brower.delegate = self
        brower.sourceImagesContainerView = collectionView
        brower.imageCount = arrayImage.count
        brower.isDelete = true
        brower.currentImageIndex = index
        brower.isAutoDelete = true
        brower.show()
    }
}

extension KcSelectImageShowView: SDPhotoBrowserDelegate {
    public func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        return arrayImage[index]
    }
    
    /// 删除了第几张照片
    public func sd_PhotoBrowserDeleteImage(with index: Int) {
        if arrayImage.count > index {
            arrayImage.remove(at: index)
            collectionView.reloadData()
            //回调
            callback()
        }
    }
}

//MARK: 私有func
extension KcSelectImageShowView {
    // 回调
    fileprivate func callback() {
        collectionView.reloadData()
        
        if delegate != nil {
            let h = getHeight()
            delegate?.kcSelectImageShowView!(self, finishImageArray: arrayImage, contentHeight: h)
        }
        if finishBlock != nil {
            let h = getHeight()
            finishBlock!(self, arrayImage, h)
        }
    }
    
    fileprivate func getHeight() -> CGFloat {
        return KcSelectImageShowView.getHeight(frame.size.width, array: arrayImage, maxImagesCount: maxImagesCount)
    }
    override public func layoutSubviews() {
        super.layoutSubviews()
        
        collectionView.frame = bounds
    }
}

//MARK: 相机选择
extension KcSelectImageShowView {
    func openCamera() {
        if !(isRearCameraAvailable()) {
            showMessage()
            return
        }
        //iOS判断应用是否有使用相机的权限
        let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
        
        if(authStatus == .restricted || authStatus == .denied) {
            showMessage()
            return
        }
        show()
    }
    
    private func show(_ isCamera: Bool = true) {
        let picker = UIImagePickerController()
        if isCamera {
            picker.sourceType = .camera
        }
        else {
            picker.sourceType = .photoLibrary
        }
        picker.allowsEditing = false
        picker.delegate =  self
        viewController?.present(picker, animated: true, completion: nil)
    }
    
    private func showMessage(_ isCamera: Bool = true) {
        let appCurName = getBundleName()
        let title = isCamera ? "相机" : "相册"
        let alert = UIAlertView(title: nil, message: "请在iPhone的“设置-隐私-\(title)”选项中，允许\(appCurName)访问你的\(title)", delegate: self, cancelButtonTitle: "好")
        alert.show()
    }
    //获取工程的名字
    fileprivate func getBundleName() -> String {
        let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String  //这里也是坑，请不要翻译oc的代码，而是去NSBundle类里面看它的api
        return appName!
    }
    // 后面的摄像头是否可用
    fileprivate func isRearCameraAvailable() -> Bool {
        return UIImagePickerController.isCameraDeviceAvailable(.rear)
    }
}

//MARK: 相机获取照片
extension KcSelectImageShowView : UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage]
        guard let icon = image as? UIImage else { return }
        let data = UIImageJPEGRepresentation(icon, 0.3)
        if data == nil { return }
        let impressImage = UIImage(data: data!)
        guard let i = impressImage else { return }

        arrayImage.append(i)
        callback()
        picker.dismiss(animated: true, completion: nil)
    }
}
